package com.gxa.insurance.service.impl;

import com.gxa.insurance.exception.BusinessException;
import com.gxa.insurance.exception.ExceptionCode;
import com.gxa.insurance.mapper.OrderMapper;
import com.gxa.insurance.mapper.PayMapper;
import com.gxa.insurance.pojo.*;
import com.gxa.insurance.service.OrderService;
import com.gxa.insurance.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Min
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper mapper;
    @Autowired
    private PayMapper payMapper;

    @Override
    public List<Order> selectNotReturnedOrder() throws Exception {
        List<Order> orders = mapper.selectNotReturnedOrder();
        if (orders.size() < 1) {
            throw new BusinessException(ExceptionCode.EMPTY_LIST);
        }
        return orders;
    }

    @Override
    public Order selectOrderByNumber(String number) throws Exception {
        Order order = mapper.selectOrderByNumber(number);
        if (order == null) {
            throw new BusinessException(ExceptionCode.EMPTY_LIST);
        }
        return order;
    }

    @Override
    public List<Order> selectAllOrderList() throws Exception {
        List<Order> orders = mapper.selectAllOrderList();
        if (orders.size() < 1) {
            throw new BusinessException(ExceptionCode.EMPTY_LIST);
        }
        return orders;
    }


    @Override
    public Map<String, Object> selectAllOrder(Map<String, Integer> map) throws Exception {
        if (map.get("page") <= 0 || map.get("page") == null) {
            map.put("page", 1);
        }
        if (map.get("pageSize") <= 0 || map.get("pageSize") == null) {
            map.put("pageSize", 10);
        }
        map.put("page", (map.get("page") - 1) * map.get("pageSize"));
        List<Order> orders = mapper.selectAllOrder(map);

        Integer count = mapper.selectAllOrderCount();

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("list", orders);
        returnMap.put("count", count);
        if (orders.size() < 1) {
            throw new BusinessException(ExceptionCode.EMPTY_LIST);
        }
        return returnMap;
    }

    @Override
    public List<OrderType> selectAllType() {
        List<OrderType> orderTypes = mapper.selectAllOrderType();
        return orderTypes;
    }

    @Override
    public List<String> selectAllSource() {
        List<OrderSource> orderSources = mapper.selectAllSource();
        List<String> sources = new ArrayList<>();

        for (int i = 0; i < orderSources.size(); i++) {
            sources.add(orderSources.get(i).getOrderSource());
        }
        return sources;
    }

    @Override
    public List<OrderStatus> selectAllStatus() {
        List<OrderStatus> orderStatuses = mapper.selectAllStatus();
//        List<String> status = new ArrayList<>();
//
//        for (int i = 0; i < orderStatuses.size(); i++) {
//            status.add(orderStatuses.get(i).getOrderStatus());
//        }
        return orderStatuses;
    }

    @Override
    public Map<String, Object> selectByLike(Map map) throws ParseException {
        Map<String, Object> maps = new HashMap<>();


        // 转换传入的时间字符串对象
        Object createTime = map.get("createTime");
        Object overTime = map.get("overTime");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        if (createTime != null && !"".equals(createTime)) {
            Date create = simpleDateFormat.parse(String.valueOf(createTime));
            map.put("createTime", create);
        }
        if (overTime != null && !"".equals(overTime)) {
            Date over = simpleDateFormat.parse(String.valueOf(overTime));
            map.put("overTime", over);
        }
        // 处理page 和 pageSize
        Object page = map.get("page");
        Object pageSize = map.get("pageSize");
        // 类型转换
        int intPage = Integer.parseInt(String.valueOf(page));
        int intPageSize = Integer.parseInt(String.valueOf(pageSize));
        if (intPage <= 0) {
            intPage = 1;
        } else if (intPageSize <= 0) {
            intPageSize = 10;
        }
        map.put("page", (intPage - 1) * intPageSize);
        map.put("pageSize", intPageSize);
        // 调用 mapper 查询
        List<Order> orders = mapper.selectByLike(map);
        Integer count = mapper.selectByfLikeCount(map);
        maps.put("list", orders);
        maps.put("count", count);
        return maps;
    }

    @Transactional
    @Override
    public Boolean addByBackStage(Map<String, String> map) throws Exception {
        // 创建支付订单
        Pay pay = new Pay();
        String PayNumber = UUID.randomUUID().toString().replace("-", "");
        pay.setStatus(false);
        pay.setNumber(PayNumber);
        pay.setTotal("2500");
        payMapper.addInitPayOrder(pay);
        // 将传入的值转换成Order对象
        Order order = new Order();
        order.setNumber(UUID.randomUUID().toString().replace("-", ""));
        order.setCarId(map.get("carId"));
        order.setDiver(map.get("driver"));
        order.setDriverArea(map.get("driverArea"));
        order.setName(map.get("username"));
        order.setPhone(map.get("phone"));
        // 添加订单状态
        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setId(Integer.parseInt(map.get("statusId")));
        orderStatus.setOrderStatus(map.get("orderStatus"));
        order.setStatus(orderStatus);

        OrderSource orderSource = new OrderSource();
        orderSource.setId(1);
        orderSource.setOrderSource("后台");
        order.setOrderSource(orderSource);

        OrderType orderType = new OrderType();
        orderType.setOrderType(map.get("type"));
        orderType.setTypeId(Integer.parseInt(map.get("typeId")));
        order.setOrderType(orderType);

        order.setCreateTime(new Date(System.currentTimeMillis()));
        order.setPay(pay);

        // 创建订单表并返回id
        Integer Arow = mapper.addOrderByBackstage(order);

        // 获取到已存储的总订单id
        Integer dbOrderId = order.getId();
        //根据订单类型创建 相应的订单详情
        switch (order.getOrderType().getOrderType()) {
            case "理赔":
                //创建订单
                InsuranceOrder insuranceOrder = new InsuranceOrder();
                insuranceOrder.setOrderId(dbOrderId);
                insuranceOrder.setReceivePosition(map.get("receivePosition"));
                insuranceOrder.setEngineNumber(map.get("engineNumber"));
                insuranceOrder.setGetCarTime(new Date(System.currentTimeMillis()));
                insuranceOrder.setTip(map.get("tip"));
                Area area = new Area();
                area.setArea(map.get("s4Area"));
                insuranceOrder.setS4Area(area);
                S4Shop s4Shop = new S4Shop();
                s4Shop.setName(map.get("s4Shop"));
                insuranceOrder.setS4Shop(s4Shop);
                RepairDepot repairDepot = new RepairDepot();
                repairDepot.setArea(map.get("inspectArea"));
                repairDepot.setName(map.get("inspectName"));
                insuranceOrder.setInspectPlace(repairDepot);
                // 调用mapper
                mapper.addInitInsuranceOrder(insuranceOrder);
                break;
            case "验车":
                //创建订单
                InspectOrder inspectOrder = new InspectOrder();
                inspectOrder.setOrderId(dbOrderId);
                inspectOrder.setReceivePosition(map.get("receivePosition"));
                inspectOrder.setEngineNumber(map.get("engineNumber"));
                inspectOrder.setGetCarTime(new Date(System.currentTimeMillis()));
                inspectOrder.setTips(map.get("tip"));
                Area area1 = new Area();
                area1.setId(Integer.parseInt(map.get("s4AreaId")));
                area1.setArea(map.get("s4Area"));
                inspectOrder.setS4Area(area1);
                S4Shop s4Shop1 = new S4Shop();
                s4Shop1.setName(map.get("s4Shop"));
                inspectOrder.setS4_shop(s4Shop1);
                RepairDepot repairDepot1 = new RepairDepot();
                repairDepot1.setArea(map.get("inspectArea"));
                repairDepot1.setName(map.get("inspectName"));
                inspectOrder.setInspectPlace(repairDepot1);
                // 调用mapper
                mapper.addInitInspectOrder(inspectOrder);
                break;
            case "领标":
                //创建订单
                BringTheOrder bringTheOrder = new BringTheOrder();
                bringTheOrder.setOrderId(dbOrderId);
                bringTheOrder.setReceivePosition(map.get("receivePosition"));
                bringTheOrder.setEngineNumber(map.get("engineNumber"));
                bringTheOrder.setGetCarTime(new Date(System.currentTimeMillis()));
                bringTheOrder.setTip(map.get("tip"));
                RepairDepot repairDepot2 = new RepairDepot();
                repairDepot2.setArea(map.get("inspectArea"));
                repairDepot2.setName(map.get("inspectName"));
                bringTheOrder.setInspectPlace(repairDepot2);
                // 调用mapper
                mapper.addInitBringTheOrder(bringTheOrder);
                break;
            case "新车上牌":
                //创建订单
                NewCarOrder newCarOrder = new NewCarOrder();
                newCarOrder.setOrderId(dbOrderId);
                newCarOrder.setCreateTime(new Date(System.currentTimeMillis()));
                newCarOrder.setTip(map.get("tip"));
                RepairDepot repairDepot3 = new RepairDepot();
                repairDepot3.setArea(map.get("inspectArea"));
                repairDepot3.setName(map.get("inspectName"));
                newCarOrder.setInspectPlace(repairDepot3);
                // 调用mapper
                mapper.addInitNewCarOrder(newCarOrder);
                break;
            case "异地委托函":
                //创建订单
                RemoteOrder remoteOrder = new RemoteOrder();
                remoteOrder.setOrderId(dbOrderId);
                remoteOrder.setCreateTime(new Date(System.currentTimeMillis()));
                remoteOrder.setTip(map.get("tip"));
                // 调用mapper
                mapper.addInitRemoteOrder(remoteOrder);
                break;
            default:
                throw new BusinessException(ExceptionCode.WRONG_ORDER_TYPE);
        }
        return true;
    }

    @Override
    public List<Order> getPayNumber(String orderNumber) throws Exception {
        List<Order> orders = mapper.selectByNumber(orderNumber);
        if (orders.size() == 0) {
            throw new BusinessException(ExceptionCode.PAYNUMBER_NOT_FOUND);
        }
        return orders;
    }

    @Transactional
    @Override
    public Boolean deleteBatch(String ids) {
        // 将ids解析为list
        String[] split = ids.split(",");
        List<Integer> intIds = new ArrayList<>();
        List<String> stringId = Arrays.asList(split);
        // 将id转换成Integer
        for (int i = 0; i < stringId.size(); i++) {
            intIds.add(Integer.parseInt(stringId.get(i)));
        }
        List<String> orderTypes = new ArrayList<>();
        // 查出所有id的订单类型
        for (Integer id : intIds) {
            String type = mapper.selectOrderTypeById(id);
            orderTypes.add(type);
        }
        // 根据Orderid删除所有 详情订单
        for (int i = 0; i < intIds.size(); i++) {
            if ("理赔".equals(orderTypes.get(i))) {
                mapper.deleteInsuranceByOrderId(intIds.get(i));
            } else if ("验车".equals(orderTypes.get(i))) {
                mapper.deleteInspectByOrderId(intIds.get(i));
            } else if ("领标".equals(orderTypes.get(i))) {
                mapper.deleteBringTheByOrderId(intIds.get(i));
            } else if ("新车上牌".equals(orderTypes.get(i))) {
                mapper.deleteNewCarByOrderId(intIds.get(i));
            } else if ("异地委托函".equals(orderTypes.get(i))) {
                mapper.deleteRemoteByORderId(intIds.get(i));
            }
        }
        List<Integer> payIds = new ArrayList<>();
        // 根据OrderId查找支付订单Id
        for (Integer id : intIds) {
            Integer payId = mapper.selectPayIdByOrderId(id);
            payIds.add(payId);
        }
        // 删除pay订单根据OrderId
        mapper.deletePays(payIds);
        // 批量删除
        mapper.deleteOrders(intIds);
        return true;
    }

    @Override
    public Map<String, List<Map<String, Object>>> getOrder() {
        Map<String, List<Map<String, Object>>> map = new HashMap();
        List<OrderType> orderTypes = mapper.selectAllOrderType();
        for (int i = 0; i < orderTypes.size(); i++) {
            if ("理赔".equals(orderTypes.get(i).getOrderType())) {
                List<Map<String, Object>> insurances = mapper.getOrderByTypeInsurance();
                map.put("insurances", insurances);
            } else if ("验车".equals(orderTypes.get(i).getOrderType())) {
                List<Map<String, Object>> inspect = mapper.getOrderByTypeInspect();
                map.put("inspect", inspect);
            } else if ("领标".equals(orderTypes.get(i).getOrderType())) {
                List<Map<String, Object>> bring = mapper.getOrderByTypeBring();
                map.put("bring", bring);
            } else if ("新车上牌".equals(orderTypes.get(i).getOrderType())) {
                List<Map<String, Object>> newCar = mapper.getOrderByTypeNewCar();
                map.put("newCar", newCar);
            } else if ("异地委托函".equals(orderTypes.get(i).getOrderType())) {
                List<Map<String, Object>> remote = mapper.getOrderByTypeRemote();
                map.put("remote", remote);
            }
        }
        return map;
    }

    @Transactional
    @Override
    public Boolean updateInspectByOrder(Map<String, String> map) throws ParseException, BusinessException {
        // 封装类型
        // 从数据库中将此订单编号的Order查询出来
        Order dbOrder = mapper.selectOrderByNumber(map.get("number"));
        if(dbOrder==null){
            throw new BusinessException(ExceptionCode.UPDATE_FILED);
        }
        // 通过查询出来的修改
        dbOrder.setDiver(map.get("getDriver"));
        dbOrder.setDriverArea(map.get("getDriverArea"));
        dbOrder.setReturnDriver(map.get("reDriver"));
        dbOrder.setReturnArea(map.get("returnArea"));
        OrderStatus orderStatus = mapper.selectOrderStatus(map.get("orderStatus"));
        dbOrder.setStatus(orderStatus);

        dbOrder.setWorkCompany(map.get("workCompany"));
        dbOrder.setCarId(map.get("carId"));
        mapper.updateOrder(dbOrder);

        InspectOrder inspectOrder = mapper.selectInspectOrder(dbOrder.getId());
        if(inspectOrder==null){
            throw new BusinessException(ExceptionCode.UPDATE_FILED);
        }
        RepairDepot repairDepot = new RepairDepot();
        repairDepot.setName(map.get("inspectPlace"));
        repairDepot.setArea(map.get("inspectArea"));
        inspectOrder.setInspectPlace(repairDepot);
        inspectOrder.setIsMakeCompemsation(Boolean.valueOf(map.get("isMakeCompemsation")));
        inspectOrder.setIsSendMessage(Boolean.valueOf(map.get("isSendMessage")));

        inspectOrder.setAttention(map.get("attention"));
        inspectOrder.setMessageContent(map.get("cusMessage"));
        inspectOrder.setMessageDri(map.get("driMessage"));
        inspectOrder.setMessageOperate(Integer.parseInt(map.get("messageOperate")));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Date getCarTime = simpleDateFormat.parse(map.get("getCarTime"));
        inspectOrder.setGetCarTime(getCarTime);
        inspectOrder.setEngineNumber(map.get("engineNumber"));
        inspectOrder.setContactPerson(map.get("contactPerson"));
        inspectOrder.setContactPhone(map.get("contactPhone"));
        inspectOrder.setRegisterPerson(map.get("registerP"));
        inspectOrder.setReceivePosition(map.get("receiveP"));
        inspectOrder.setReturnPosition(map.get("returnP"));
        inspectOrder.setReceiveMap(map.get("receiveMap"));
        inspectOrder.setReturnMap(map.get("returnMap"));
        inspectOrder.setTips(map.get("tip"));
        Date returnTime = simpleDateFormat.parse(map.get("returnTime"));
        inspectOrder.setReturnTime(returnTime);
        inspectOrder.setPictureDesc(map.get("pictureDesc"));
        mapper.updateInspectOrder(inspectOrder);

        // 根据order的id 插入图片表
        String damageImg = map.get("damageImg");
        String attachmentImg = map.get("attachmentImg");

        if (!StringUtil.isEmpty(damageImg)) {
            String[] imagPath = damageImg.split(",");
            List<String> damagePath = Arrays.asList(imagPath);

            for (int i = 0; i < damagePath.size(); i++) {
                mapper.insertDamageImage(dbOrder.getId(), damagePath.get(i));
            }
        }
        if (!StringUtil.isEmpty(attachmentImg)) {
            String[] imagPath2 = attachmentImg.split(",");
            List<String> attachmentPath = Arrays.asList(imagPath2);
            for (int i = 0; i < attachmentPath.size(); i++) {
                mapper.insertAttachmentImage(dbOrder.getId(), attachmentPath.get(i));
            }
        }
        return true;
    }

    @Override
    public Integer updateOrderStatusByNumber(String number, String orderStatus) throws Exception {
        Integer update = mapper.updateOrderStatusByNumber(number, orderStatus);
        if (update != 1) {
            throw new BusinessException(ExceptionCode.UPDATE_ORDER_FAILED);
        }
        return update;
    }



        @Override
        public List<Order> selectOrderDetails(Integer id) throws BusinessException {
            List<Order> orders = mapper.selectOrderDetails(id);
            if (orders.size()==0){
                throw new BusinessException(ExceptionCode.EMPTY_LIST);
            }

            return orders;
        }



    @Transactional
    @Override
    public Boolean updateInsuranceByOrder(Map<String, String> map) throws ParseException, BusinessException {
        // 封装类型
        // 从数据库中将此订单编号的Order查询出来
        Order dbOrder = mapper.selectOrderByNumber(map.get("number"));
        if(dbOrder==null){
            throw new BusinessException(ExceptionCode.UPDATE_FILED);
        }
        // 通过查询出来的修改
        dbOrder.setDiver(map.get("getDriver"));
        dbOrder.setDriverArea(map.get("getDriverArea"));
        dbOrder.setReturnDriver(map.get("reDriver"));
        dbOrder.setReturnArea(map.get("returnArea"));
        dbOrder.setWorkCompany(map.get("workCompany"));
        OrderStatus orderStatus = mapper.selectOrderStatus(map.get("orderStatus"));
        dbOrder.setStatus(orderStatus);
        dbOrder.setCarId(map.get("carId"));
        mapper.updateOrder(dbOrder);
        //更新 订单详情
        InsuranceOrder dbInOrder = mapper.selectInsuranceByOrderId(dbOrder.getId());
        if(dbInOrder==null){
            throw new BusinessException(ExceptionCode.UPDATE_FILED);
        }
        S4Shop s4Shop = new S4Shop();
        s4Shop.setArea(map.get("s4ShopArea"));
        s4Shop.setName(map.get("s4ShopName"));
        dbInOrder.setS4Shop(s4Shop);

        dbInOrder.setIsFiveCirecle(Boolean.valueOf(map.get("isFiveC")));
        dbInOrder.setIsMakeCompemsation(Boolean.valueOf(map.get("isMakeCom")));
        dbInOrder.setIsSendMessage(Boolean.valueOf(map.get("isSendMess")));
        dbInOrder.setAttention(map.get("attention"));
        dbInOrder.setMessageContentCus(map.get("cusMessageC"));
        dbInOrder.setMessageOperate(Integer.parseInt(map.get("messageOperation")));
        dbInOrder.setMessageContentDri(map.get("driMessageC"));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        Date getCarTime = simpleDateFormat.parse(map.get("getCarTime"));
        dbInOrder.setGetCarTime(getCarTime);
        dbInOrder.setEngineNumber(map.get("engineNumber"));
        dbInOrder.setInsuredPerson(map.get("insurancedPerson"));
        dbInOrder.setContactPerson(map.get("contactPerson"));
        dbInOrder.setContactPhone(map.get("contactPhone"));
        dbInOrder.setPosition(map.get("damagePosition"));
        dbInOrder.setRegisterPerson(map.get("registerP"));
        dbInOrder.setReceivePosition(map.get("receiveP"));
        dbInOrder.setReturnPosition(map.get("returnP"));
        dbInOrder.setReceiveMap(map.get("receiveMap"));
        dbInOrder.setReturnMap(map.get("returnMap"));
        dbInOrder.setTip(map.get("tip"));
        Date completeTime = simpleDateFormat.parse(map.get("completeTime"));
        dbInOrder.setCompleteTime(completeTime);
        dbInOrder.setPictureDesc(map.get("pictureDesc"));
        mapper.updateInsurance(dbInOrder);

        // 根据order的id 插入图片表
        String damageImg = map.get("damageImg");
        String attachmentImg = map.get("attachmentImg");

        if (!StringUtil.isEmpty(damageImg)) {
            String[] imagPath = damageImg.split(",");
            List<String> damagePath = Arrays.asList(imagPath);

            for (int i = 0; i < damagePath.size(); i++) {
                mapper.insertDamageImage(dbOrder.getId(), damagePath.get(i));
            }
        }
        if (!StringUtil.isEmpty(attachmentImg)) {
            String[] imagPath2 = attachmentImg.split(",");
            List<String> attachmentPath = Arrays.asList(imagPath2);
            for (int i = 0; i < attachmentPath.size(); i++) {
                mapper.insertAttachmentImage(dbOrder.getId(), attachmentPath.get(i));
            }
        }

        return true;
    }

    @Override
    public Map<String, Object> selectDetailByNumberAndType(Map<String, String> map) throws BusinessException {
        // 取出map相应数据
        String number = map.get("number");
        String type = map.get("type");
        if (StringUtil.isEmpty(number) || StringUtil.isEmpty(type)) {
            throw new BusinessException(ExceptionCode.WRONG_VALUE);
        }
        Map<String, Object> results = new HashMap<>();
        // 先将本Order查询出来
        Order order = mapper.selectOrderByNumber(number);
        results.put("order", order);
        if ("理赔".equals(type)) {
            InsuranceOrder inOrder = mapper.selectInsuranceByOrderId(order.getId());
            results.put("detail", inOrder);
            List<Image> damageImg = mapper.selectDamageImgByOrderId(order.getId());
            List<Image> attachmentImg = mapper.selectAttachmentImgByOrderId(order.getId());
            results.put("damageImg", damageImg);
            results.put("attachmentImg", attachmentImg);
        } else if ("验车".equals(type)) {
            InspectOrder insOrder = mapper.seleInspectByORderId(order.getId());
            results.put("detail", insOrder);
            List<Image> attachmentImg = mapper.selectAttachmentImgByOrderId(order.getId());
            results.put("attachmentImg", attachmentImg);
        } else if ("领标".equals(type)) {
            BringTheOrder bOrder = mapper.selectBringTheOrderByOrderId(order.getId());
            results.put("detail", bOrder);
            List<Image> attachmentImg = mapper.selectAttachmentImgByOrderId(order.getId());
            results.put("attachmentImg", attachmentImg);
        } else if ("新车上牌".equals(type)) {
            NewCarOrder NewOder = mapper.selectNewCarByOrderId(order.getId());
            results.put("detail", NewOder);
        } else if ("异地委托函".equals(type)) {
            RemoteOrder RORder = mapper.selectRemoteByORderId(order.getId());
            results.put("detail", RORder);
            List<Image> attachmentImg = mapper.selectAttachmentImgByOrderId(order.getId());
            results.put("attachmentImg", attachmentImg);
        }

        // 根据OrderId查询Pay订单
//        System.out.println(order.getPay().getId());
//        Pay pay = mapper.selectPayByOrderId(order.getPay().getId());
//        results.put("pay", pay);
        return results;
    }
}
